package database

import (
	"cqsx/database"
	"crypto/md5"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/howeyc/gopass"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type classmate struct {
	Id        int
	Name      string
	Sn        string
	Sex       string
	Classname string
	Pswd      string
}

func init() {
	dsn := "root:123456@tcp(172.14.1.66:3306)/classmates?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("链接数据库失败，原因是：", err.Error())
		return
	}
	fmt.Println("连接成功", db)

}

var db *gorm.DB
var LoginUser classmate

func DBDEmo() {
	dsn := "root:123456@tcp(172.14.1.66:3306)/classmates?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("链接数据库失败，原因是：", err.Error())
		return
	}
	fmt.Println("连接成功", db)
	//var zhangsan classmate
	//zhangsan.Name = "张三"
	//zhangsan.Sex = "男"
	//zhangsan.Sn = "123456"
	//tx := db.Save(&zhangsan)
	//fmt.Println(tx)

	for {

		var xhw classmate
		var findname string
		fmt.Println("输入姓名")
		fmt.Scanln(&findname)
		db.Where("name = ?", findname).First(&xhw)
		fmt.Println(xhw.Name)
		fmt.Println(xhw.Sn)
		fmt.Println(xhw.Classname)
		fmt.Println("++++++++++++++++")
	}
}

func Register(user *classmate) {
	db.Save(user)
}

func Login() bool {
	var name string
	fmt.Println("请输入用户名：")
	fmt.Scanln(&name)

	var pswd string
	fmt.Println("-----------")
	//fmt.Scanln(&pswd)

	pswdBytes, err := gopass.GetPasswdPrompt("请输入密码：", true, os.Stdin, os.Stdout)
	if err != nil {
		fmt.Println("GetPasswdPrompt 失败，", err.Error())
		return false
	}
	pswd = string(pswdBytes)
	pswd = fmt.Sprintf("%x", md5.Sum([]byte(pswd)))

	db.Raw("SELECT * FROM classmates.classmates where name = ?", name).Scan(&LoginUser)
	if LoginUser.Pswd == pswd {
		fmt.Println("登录成功，欢迎您！", LoginUser.Name)
		return true
	} else {
		fmt.Println("登录失败!")
		return false
	}
}

func ResetPswd() {
	var oldPswd string
	fmt.Println("请输入当前密码进行验证：")
	fmt.Scanln(&oldPswd)
	oldPswd = fmt.Sprintf("%x", md5.Sum([]byte(oldPswd)))

	if LoginUser.Pswd != oldPswd {
		fmt.Println("您输入的密码错误！")
		return
	}

	var newPswd string
	fmt.Println("请输入新密码：")
	fmt.Scanln(&newPswd)

	var newPswdAgain string
	fmt.Println("请再次输入新密码进行验证：")
	fmt.Scanln(&newPswdAgain)
	if newPswd != newPswdAgain {
		fmt.Println("两次输入的密码不一致，请重试！")
		return
	}
	LoginUser.Pswd = fmt.Sprintf("%x", md5.Sum([]byte(newPswd)))
	db.Save(&LoginUser)
	fmt.Println("修改密码成功！")
}

type Records struct {
	ID         int
	Name       string
	Sn         string
	Tel        string
	Comments   string
	Classid    int
	Createtime time.Time
	Classroom  string
}

func Jiafen() {
	for {
		var name string
		fmt.Println("请输入你想修改分数的人的名字")
		fmt.Scanln(&name)
		var recordsList []Records
		db.Raw(`select * from classmates.records where name = ?`, name).Scan(&recordsList)
		for _, record := range recordsList {
			fmt.Printf("id:%5d,名字%10s分数:%10s考勤时间是:%20v \n", record.ID, record.Name, record.Comments, record.Createtime)
		}

		var id string
		fmt.Println("请输入你想修改的人的id")
		fmt.Scanln(&id)
		var fenshu string
		fmt.Println("请输入你想修改的分数")
		fmt.Scanln(&fenshu)
		db.Exec(`UPDATE classmates.records SET comments=?
		 WHERE id = ?;`, fenshu, id)

		db.Raw(`select * from classmates.records where name = ?`, name).Scan(&recordsList)
		for _, record := range recordsList {
			fmt.Printf("id:%5d,名字%10s分数:%10v考勤时间是:%20v \n", record.ID, record.Name, record.Comments, record.Createtime)
		}

	}
}

func SaveStudentRecords() {
	var allStudents []database.Classmate
	database.DB.Raw("SELECT*FROM classmates.classmates").Scan(&allStudents)
	for _, stu := range allStudents {
		mulu := "D:/go语言/" + strconv.Itoa(stu.ClassId)
		cuowu := os.MkdirAll(mulu, os.ModeDir)
		if cuowu != nil {
			fmt.Println("创建目录的时候出错，错误信息是：", cuowu)
			return
		}
		fmt.Println("创建的目录是：", mulu+"/"+stu.Sn+stu.Name+".txt")
		currentFile, err := os.Create(mulu + stu.Sn + stu.Name + ".txt")
		if err != nil {
			fmt.Println("创建失败的原因是：", err)
			return
		}
		fmt.Println("正在处理" + stu.Name + "的数据，请耐心等待...\n")
		var thisStudentRecord []database.Records
		database.DB.Raw("select*from classmates.records where sn=?", stu.Sn).Scan(&thisStudentRecord)
		currentFile.WriteString("面向对象程序设计的考勤记录\n")
		for _, records := range thisStudentRecord {
			currentFile.WriteString(records.Name + records.Createtime.String() + records.Comments + "\n")
		}
		currentFile.WriteString("以上就是该同学的所有考勤记录。等级时间是：" + time.Now().String())
		currentFile.Close()
	}

}
